#include "ioctl.h"

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <linux/hdreg.h>


bool ioctrl::scan_disk(std::set<std::string> &disks) {
  disks.clear();

  FILE *f = ::fopen("/proc/partitions", "r");
  if (!f) return false;

  char line[100], dev[100];
  int max, min, size;
  char *s;
  while (fgets(line, sizeof(line), f)) {
    if (sscanf(line, " %u %u %u %[^\n]"
      , &max, &min, &size, dev) != 4) {
      continue;
    }
    for (s = dev; *s; ++s)
      continue;
    if (s[-1] >= '1' && s[-1] <= '9')
      continue;

    disks.insert(dev);
  }

  ::fclose(f);
  return true;
}

bool ioctrl::disk_info(const std::string dev) {
  if (dev.empty())
    return false;

  int fd = ::open(dev.c_str(), O_RDONLY | O_NONBLOCK);
  if (fd <= 0)
    return false;

  struct hd_driveid hd = { 0 };
  if(!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
    ::close(fd);
    return false;
  }

  printf("dev:%s\n", dev.c_str());
  printf("serial_no:%s\n", hd.serial_no);
  printf("model:%s\n", hd.model);
  printf("model:%s\n", hd.model);

  ::close(fd);

  if(!ioctl(fd, WIN_IDENTIFY, &hd)) {
    ::close(fd);
    return false;
  }
  return true;
}